import React, { useState, useEffect, useRef } from 'react';
import { Socket } from 'socket.io-client';
import './VideoCall.css';

interface VideoCallProps {
  isVisible: boolean;
  onClose: () => void;
  otherUser: {
    username: string;
    image: string;
  };
  currentUser: {
    username: string;
    image: string;
  };
  socket: Socket | null;
  isIncoming?: boolean;
  incomingOffer?: RTCSessionDescriptionInit;
  onCallStateChange?: (state: 'connected' | 'ended' | 'rejected') => void;
  callState?: 'idle' | 'calling' | 'connected' | 'ended';
  onCallEnded?: (duration: number) => void;
  isCallInitiator?: boolean;
}

const VideoCall: React.FC<VideoCallProps> = ({
  isVisible,
  onClose,
  otherUser,
  currentUser,
  socket,
  isIncoming: isIncomingCall = false,
  incomingOffer,
  onCallStateChange,
  callState: externalCallState,
  onCallEnded,
  isCallInitiator = false,
}) => {
  const [isIncoming, setIsIncoming] = useState(isIncomingCall);
  const [isCallActive, setIsCallActive] = useState(false);
  const [isMuted, setIsMuted] = useState(false);
  const [isVideoEnabled, setIsVideoEnabled] = useState(true);
  const [callDuration, setCallDuration] = useState(0);
  const [localStream, setLocalStream] = useState<MediaStream | null>(null);
  const [remoteStream, setRemoteStream] = useState<MediaStream | null>(null);
  const [isConnecting, setIsConnecting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const peerConnectionRef = useRef<RTCPeerConnection | null>(null);
  const localVideoRef = useRef<HTMLVideoElement>(null);
  const remoteVideoRef = useRef<HTMLVideoElement>(null);
  const durationIntervalRef = useRef<NodeJS.Timeout | null>(null);
  const startTimeRef = useRef<number>(0);
  const connectionTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  const rtcConfig: RTCConfiguration = {
    iceServers: [
      { urls: 'stun:stun.l.google.com:19302' },
      { urls: 'stun:stun1.l.google.com:19302' },
      { urls: 'stun:stun2.l.google.com:19302' },
      { urls: 'stun:stun3.l.google.com:19302' },
      { urls: 'stun:stun4.l.google.com:19302' },
      { urls: 'stun:stun.ekiga.net' },
      { urls: 'stun:stun.ideasip.com' },
      { urls: 'stun:stun.rixtelecom.se' },
      { urls: 'stun:stun.schlund.de' },
      { urls: 'stun:stun.stunprotocol.org:3478' },
      { urls: 'stun:stun.voiparound.com' },
      { urls: 'stun:stun.voipbuster.com' },
      { urls: 'stun:stun.voipstunt.com' },
      { urls: 'stun:stun.voxgratia.org' },
      { urls: 'stun:stun.xten.com' },
    ],
    iceCandidatePoolSize: 10,
    iceTransportPolicy: 'all' as RTCIceTransportPolicy,
    bundlePolicy: 'max-bundle' as RTCBundlePolicy,
    rtcpMuxPolicy: 'require' as RTCRtcpMuxPolicy,
  };

  // 初始化视频元素
  useEffect(() => {
    if (localVideoRef.current) {
      localVideoRef.current.muted = true;
      localVideoRef.current.playsInline = true;
      localVideoRef.current.autoplay = true;
      localVideoRef.current.controls = false;

      // 添加事件监听器
      localVideoRef.current.addEventListener('loadedmetadata', () => {
        console.log('VideoCall: 本地视频元数据加载完成');
      });

      localVideoRef.current.addEventListener('canplay', () => {
        console.log('VideoCall: 本地视频可以播放');
      });

      localVideoRef.current.addEventListener('play', () => {
        console.log('VideoCall: 本地视频开始播放');
      });

      localVideoRef.current.addEventListener('error', e => {
        console.error('VideoCall: 本地视频播放错误:', e);
      });

      console.log('VideoCall: 本地视频元素初始化完成');
    }

    if (remoteVideoRef.current) {
      remoteVideoRef.current.muted = false;
      remoteVideoRef.current.playsInline = true;
      remoteVideoRef.current.autoplay = true;
      remoteVideoRef.current.controls = false;

      // 添加事件监听器
      remoteVideoRef.current.addEventListener('loadedmetadata', () => {
        console.log('VideoCall: 远程视频元数据加载完成');
      });

      remoteVideoRef.current.addEventListener('canplay', () => {
        console.log('VideoCall: 远程视频可以播放');
      });

      remoteVideoRef.current.addEventListener('play', () => {
        console.log('VideoCall: 远程视频开始播放');
      });

      remoteVideoRef.current.addEventListener('error', e => {
        console.error('VideoCall: 远程视频播放错误:', e);
      });

      console.log('VideoCall: 远程视频元素初始化完成');
    }
  }, []);

  useEffect(() => {
    if (isVisible) {
      if (isIncomingCall && incomingOffer) {
        handleIncomingCall(incomingOffer);
      } else {
        initializeCall();
      }
    } else {
      cleanupCall();
    }
  }, [isVisible, isIncomingCall, incomingOffer]);

  useEffect(() => {
    if (externalCallState === 'connected' && !isCallActive) {
      console.log('外部状态更新：视频通话已接通');
      setIsCallActive(true);
      setIsIncoming(false);
    } else if (externalCallState === 'ended' && isCallActive) {
      console.log('外部状态更新：视频通话已结束');
      setIsCallActive(false);
      cleanupCall();
    }
  }, [externalCallState, isCallActive]);

  useEffect(() => {
    if (!socket) return;

    const handleVideoCallRequest = (data: any) => {
      console.log('收到视频通话请求:', data);
      if (data.fromUserId !== currentUser.username) {
        handleIncomingCall(data.offer);
      }
    };

    const handleVideoCallAnswered = (data: any) => {
      console.log('收到视频通话应答:', data);
      if (peerConnectionRef.current && data.answer) {
        peerConnectionRef.current
          .setRemoteDescription(new RTCSessionDescription(data.answer))
          .then(() => {
            console.log('设置远程描述成功');
            setIsCallActive(true);
            setIsIncoming(false);
            onCallStateChange?.('connected');
          })
          .catch(error => {
            console.error('设置远程描述失败:', error);
            setError('设置远程描述失败');
          });
      }
    };

    const handleVideoCallRejected = (data: any) => {
      console.log('对方拒绝了视频通话');
      setError('对方拒绝了视频通话');
      onCallStateChange?.('rejected');
      onClose();
    };

    const handleVideoCallEnded = (data: any) => {
      console.log('对方结束了视频通话');
      setError('对方结束了视频通话');
      onCallStateChange?.('ended');
      onClose();
    };

    const handleIceCandidate = (data: any) => {
      console.log('收到ICE候选者:', data);
      if (peerConnectionRef.current && data.candidate) {
        try {
          const iceCandidate = new RTCIceCandidate(data.candidate);
          peerConnectionRef.current
            .addIceCandidate(iceCandidate)
            .then(() => {
              console.log('ICE候选者添加成功');
            })
            .catch(error => {
              console.error('ICE候选者添加失败:', error);
            });
        } catch (error) {
          console.error('ICE候选者格式错误:', error);
        }
      }
    };

    const handleCallError = (data: any) => {
      console.error('通话错误:', data.message);
      setError(data.message || '通话失败');
      onClose();
    };

    socket.on('video_call_request', handleVideoCallRequest);
    socket.on('video_call_answered', handleVideoCallAnswered);
    socket.on('video_call_rejected', handleVideoCallRejected);
    socket.on('video_call_ended', handleVideoCallEnded);
    socket.on('ice_candidate', handleIceCandidate);
    socket.on('call_error', handleCallError);

    return () => {
      socket.off('video_call_request', handleVideoCallRequest);
      socket.off('video_call_answered', handleVideoCallAnswered);
      socket.off('video_call_rejected', handleVideoCallRejected);
      socket.off('video_call_ended', handleVideoCallEnded);
      socket.off('ice_candidate', handleIceCandidate);
      socket.off('call_error', handleCallError);
    };
  }, [socket, currentUser.username, onCallStateChange, onClose]);

  useEffect(() => {
    if (isCallActive) {
      startTimeRef.current = Date.now();
      durationIntervalRef.current = setInterval(() => {
        setCallDuration(Math.floor((Date.now() - startTimeRef.current) / 1000));
      }, 1000);
    } else {
      if (durationIntervalRef.current) {
        clearInterval(durationIntervalRef.current);
        durationIntervalRef.current = null;
      }
    }

    return () => {
      if (durationIntervalRef.current) {
        clearInterval(durationIntervalRef.current);
      }
    };
  }, [isCallActive]);

  const initializeCall = async () => {
    try {
      console.log('初始化视频通话...');
      setIsConnecting(true);
      setError(null);

      const stream = await navigator.mediaDevices.getUserMedia({
        video: {
          width: { ideal: 1280 },
          height: { ideal: 720 },
          facingMode: 'user',
        },
        audio: {
          echoCancellation: true,
          noiseSuppression: true,
          autoGainControl: true,
        },
      });

      console.log('获取到本地媒体流:', stream);
      setLocalStream(stream);

      // 修复视频显示：强制播放方法
      if (localVideoRef.current) {
        try {
          // 直接设置srcObject
          localVideoRef.current.srcObject = stream;
          console.log('设置本地视频srcObject完成');

          // 强制播放视频
          setTimeout(async () => {
            try {
              await localVideoRef.current?.play();
              console.log('本地视频自动播放成功');
            } catch (playError) {
              console.error('自动播放失败:', playError);

              // 如果自动播放失败，再次尝试
              setTimeout(async () => {
                try {
                  await localVideoRef.current?.play();
                  console.log('本地视频重试播放成功');
                } catch (retryError) {
                  console.error('重试播放失败:', retryError);
                }
              }, 1000);
            }
          }, 100);
        } catch (playError) {
          console.error('本地视频设置失败:', playError);
          // 如果设置失败，不中断整个流程
          setError('本地视频设置失败，但通话可以继续');
        }
      }

      const peerConnection = new RTCPeerConnection(rtcConfig);
      peerConnectionRef.current = peerConnection;

      stream.getTracks().forEach(track => {
        peerConnection.addTrack(track, stream);
      });

      peerConnection.ontrack = event => {
        console.log('收到远程流:', event.streams[0]);
        setRemoteStream(event.streams[0]);
        if (remoteVideoRef.current) {
          try {
            // 直接设置srcObject
            remoteVideoRef.current.srcObject = event.streams[0];
            console.log('设置远程视频srcObject完成');

            // 强制播放远程视频
            setTimeout(async () => {
              try {
                await remoteVideoRef.current?.play();
                console.log('远程视频自动播放成功');
              } catch (playError) {
                console.error('远程视频自动播放失败:', playError);

                // 如果自动播放失败，再次尝试
                setTimeout(async () => {
                  try {
                    await remoteVideoRef.current?.play();
                    console.log('远程视频重试播放成功');
                  } catch (retryError) {
                    console.error('远程视频重试播放失败:', retryError);
                  }
                }, 1000);
              }
            }, 100);
          } catch (error) {
            console.error('设置远程视频失败:', error);
          }
        }
      };

      peerConnection.onicecandidate = event => {
        if (event.candidate && socket) {
          console.log('发送ICE候选者:', event.candidate);
          socket.emit('ice_candidate', {
            fromUserId: currentUser.username,
            toUserId: otherUser.username,
            candidate: event.candidate,
          });
        }
      };

      peerConnection.onconnectionstatechange = () => {
        console.log('连接状态变化:', peerConnection.connectionState);
        if (peerConnection.connectionState === 'connected') {
          console.log('WebRTC连接已建立');
          setIsConnecting(false);
          if (connectionTimeoutRef.current) {
            clearTimeout(connectionTimeoutRef.current);
            connectionTimeoutRef.current = null;
          }
        } else if (peerConnection.connectionState === 'failed') {
          console.error('WebRTC连接失败');
          setError('连接失败，请检查网络连接');
          cleanupCall();
        } else if (peerConnection.connectionState === 'disconnected') {
          console.log('WebRTC连接断开');
          setIsConnecting(false);
        }
      };

      peerConnection.oniceconnectionstatechange = () => {
        console.log('ICE连接状态:', peerConnection.iceConnectionState);
        if (peerConnection.iceConnectionState === 'failed') {
          setError('ICE连接失败，请检查网络设置');
          cleanupCall();
        }
      };

      peerConnection.onicegatheringstatechange = () => {
        console.log('ICE收集状态:', peerConnection.iceGatheringState);
      };

      // 设置连接超时
      connectionTimeoutRef.current = setTimeout(() => {
        if (peerConnection.connectionState !== 'connected') {
          console.error('连接超时');
          setError('连接超时，请重试');
          cleanupCall();
        }
      }, 30000); // 30秒超时

      await initiateCall();
    } catch (error) {
      console.error('初始化视频通话失败:', error);
      if (error instanceof Error && error.name === 'NotAllowedError') {
        setError('请允许访问摄像头和麦克风权限');
      } else if (error instanceof Error && error.name === 'AbortError') {
        setError('视频播放被中断，请重试');
      } else {
        setError('无法启动摄像头，请检查设备权限');
      }
      cleanupCall();
    }
  };

  const initiateCall = async () => {
    if (!socket) {
      setError('Socket连接不可用');
      return;
    }

    try {
      console.log('发起视频通话...');
      const offer = await peerConnectionRef.current!.createOffer();
      await peerConnectionRef.current!.setLocalDescription(offer);

      socket.emit('video_call_request', {
        fromUserId: currentUser.username,
        toUserId: otherUser.username,
        fromUserName: currentUser.username,
        fromUserImage: currentUser.image,
        offer: offer,
      });
    } catch (error) {
      console.error('发起视频通话失败:', error);
      setError('发起视频通话失败');
      cleanupCall();
    }
  };

  const handleIncomingCall = async (offer: RTCSessionDescriptionInit) => {
    try {
      console.log('处理视频来电...');
      setIsConnecting(true);
      setError(null);

      // 先创建PeerConnection
      const peerConnection = new RTCPeerConnection(rtcConfig);
      peerConnectionRef.current = peerConnection;

      // 设置事件处理器
      peerConnection.ontrack = event => {
        console.log('收到远程流:', event.streams[0]);
        setRemoteStream(event.streams[0]);
        if (remoteVideoRef.current) {
          try {
            remoteVideoRef.current.srcObject = event.streams[0];
            setTimeout(async () => {
              try {
                await remoteVideoRef.current?.play();
                console.log('远程视频开始播放成功');
              } catch (playError) {
                console.error('远程视频播放失败:', playError);
              }
            }, 100);
          } catch (error) {
            console.error('设置远程视频失败:', error);
          }
        }
      };

      peerConnection.onicecandidate = event => {
        if (event.candidate && socket) {
          console.log('发送ICE候选者:', event.candidate);
          socket.emit('ice_candidate', {
            fromUserId: currentUser.username,
            toUserId: otherUser.username,
            candidate: event.candidate,
          });
        }
      };

      peerConnection.onconnectionstatechange = () => {
        console.log('连接状态变化:', peerConnection.connectionState);
        if (peerConnection.connectionState === 'connected') {
          console.log('WebRTC连接已建立');
          setIsConnecting(false);
          if (connectionTimeoutRef.current) {
            clearTimeout(connectionTimeoutRef.current);
            connectionTimeoutRef.current = null;
          }
        } else if (peerConnection.connectionState === 'failed') {
          console.error('WebRTC连接失败');
          setError('连接失败，请检查网络连接');
          cleanupCall();
        } else if (peerConnection.connectionState === 'disconnected') {
          console.log('WebRTC连接断开');
          setIsConnecting(false);
        }
      };

      peerConnection.oniceconnectionstatechange = () => {
        console.log('ICE连接状态:', peerConnection.iceConnectionState);
        if (peerConnection.iceConnectionState === 'failed') {
          setError('ICE连接失败，请检查网络设置');
          cleanupCall();
        }
      };

      peerConnection.onicegatheringstatechange = () => {
        console.log('ICE收集状态:', peerConnection.iceGatheringState);
      };

      // 设置连接超时
      connectionTimeoutRef.current = setTimeout(() => {
        if (peerConnection.connectionState !== 'connected') {
          console.error('连接超时');
          setError('连接超时，请重试');
          cleanupCall();
        }
      }, 30000); // 30秒超时

      // 尝试获取媒体流
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: {
            width: { ideal: 1280 },
            height: { ideal: 720 },
            facingMode: 'user',
          },
          audio: {
            echoCancellation: true,
            noiseSuppression: true,
            autoGainControl: true,
          },
        });
        console.log('获取到本地媒体流:', stream);
        setLocalStream(stream);

        // 设置本地视频
        if (localVideoRef.current) {
          try {
            localVideoRef.current.srcObject = stream;
            await new Promise(resolve => setTimeout(resolve, 100));
            await localVideoRef.current.play();
            console.log('本地视频开始播放成功');
          } catch (playError) {
            console.error('视频播放失败:', playError);
            setError('视频播放失败，但通话可以继续');
          }
        }

        // 添加轨道到连接
        stream.getTracks().forEach(track => {
          peerConnection.addTrack(track, stream);
        });
      } catch (mediaError) {
        console.error('获取媒体流失败:', mediaError);
        if (
          mediaError instanceof Error &&
          mediaError.name === 'NotReadableError'
        ) {
          setError('摄像头或麦克风被其他应用占用，请关闭其他应用后重试');
        } else if (
          mediaError instanceof Error &&
          mediaError.name === 'NotAllowedError'
        ) {
          setError('请允许访问摄像头和麦克风权限');
        } else {
          setError('无法启动摄像头，请检查设备权限');
        }
        // 即使没有媒体流，也继续设置远程描述
      }

      // 设置远程描述
      await peerConnection.setRemoteDescription(
        new RTCSessionDescription(offer)
      );

      // 不自动应答，让用户选择接听或拒绝
      console.log('视频来电设置完成，等待用户选择接听或拒绝');
      setIsIncoming(true);
      setIsConnecting(false);
    } catch (error) {
      console.error('处理视频来电失败:', error);
      if (error instanceof Error && error.name === 'NotAllowedError') {
        setError('请允许访问摄像头和麦克风权限');
      } else if (error instanceof Error && error.name === 'AbortError') {
        setError('视频播放被中断，请重试');
      } else {
        setError('无法启动摄像头，请检查设备权限');
      }
      // 不调用cleanupCall，保持来电界面显示
      setIsConnecting(false);
    }
  };

  const acceptCall = async () => {
    if (!socket) {
      setError('Socket连接不可用');
      return;
    }

    try {
      console.log('接听视频通话...');

      // 如果没有PeerConnection，需要重新创建
      if (!peerConnectionRef.current) {
        console.log('重新创建PeerConnection...');
        const peerConnection = new RTCPeerConnection(rtcConfig);
        peerConnectionRef.current = peerConnection;

        // 设置事件处理器
        peerConnection.ontrack = event => {
          console.log('收到远程流:', event.streams[0]);
          setRemoteStream(event.streams[0]);
          if (remoteVideoRef.current) {
            try {
              remoteVideoRef.current.srcObject = event.streams[0];
              setTimeout(async () => {
                try {
                  await remoteVideoRef.current?.play();
                  console.log('远程视频开始播放成功');
                } catch (playError) {
                  console.error('远程视频播放失败:', playError);
                }
              }, 100);
            } catch (error) {
              console.error('设置远程视频失败:', error);
            }
          }
        };

        peerConnection.onicecandidate = event => {
          if (event.candidate && socket) {
            console.log('发送ICE候选者:', event.candidate);
            socket.emit('ice_candidate', {
              fromUserId: currentUser.username,
              toUserId: otherUser.username,
              candidate: event.candidate,
            });
          }
        };

        peerConnection.onconnectionstatechange = () => {
          console.log('连接状态变化:', peerConnection.connectionState);
          if (peerConnection.connectionState === 'connected') {
            console.log('WebRTC连接已建立');
            setIsConnecting(false);
            if (connectionTimeoutRef.current) {
              clearTimeout(connectionTimeoutRef.current);
              connectionTimeoutRef.current = null;
            }
          } else if (peerConnection.connectionState === 'failed') {
            console.error('WebRTC连接失败');
            setError('连接失败，请检查网络连接');
            cleanupCall();
          } else if (peerConnection.connectionState === 'disconnected') {
            console.log('WebRTC连接断开');
            setIsConnecting(false);
          }
        };

        peerConnection.oniceconnectionstatechange = () => {
          console.log('ICE连接状态:', peerConnection.iceConnectionState);
          if (peerConnection.iceConnectionState === 'failed') {
            setError('ICE连接失败，请检查网络设置');
            cleanupCall();
          }
        };

        peerConnection.onicegatheringstatechange = () => {
          console.log('ICE收集状态:', peerConnection.iceGatheringState);
        };

        // 设置连接超时
        connectionTimeoutRef.current = setTimeout(() => {
          if (peerConnection.connectionState !== 'connected') {
            console.error('连接超时');
            setError('连接超时，请重试');
            cleanupCall();
          }
        }, 30000); // 30秒超时
      }

      // 如果没有本地流（设备被占用），尝试重新获取
      if (!localStream) {
        try {
          console.log('尝试重新获取媒体流...');
          const stream = await navigator.mediaDevices.getUserMedia({
            video: {
              width: { ideal: 1280 },
              height: { ideal: 720 },
              facingMode: 'user',
            },
            audio: {
              echoCancellation: true,
              noiseSuppression: true,
              autoGainControl: true,
            },
          });
          setLocalStream(stream);

          // 重新设置本地视频
          if (localVideoRef.current) {
            localVideoRef.current.srcObject = stream;
            await localVideoRef.current.play();
          }

          // 重新添加轨道到连接
          stream.getTracks().forEach(track => {
            peerConnectionRef.current?.addTrack(track, stream);
          });
        } catch (mediaError) {
          console.error('接听时获取媒体流失败:', mediaError);
          // 即使没有媒体流，也继续接听（可能是语音通话）
        }
      }

      // 确保有PeerConnection
      if (!peerConnectionRef.current) {
        throw new Error('PeerConnection创建失败');
      }

      const answer = await peerConnectionRef.current.createAnswer();
      await peerConnectionRef.current.setLocalDescription(answer);

      socket.emit('video_call_answer', {
        fromUserId: currentUser.username,
        toUserId: otherUser.username,
        answer: answer,
      });

      setIsIncoming(false);
      setIsCallActive(true);
      onCallStateChange?.('connected');
    } catch (error) {
      console.error('接听视频通话失败:', error);
      setError(
        '接听视频通话失败: ' +
          (error instanceof Error ? error.message : '未知错误')
      );
      cleanupCall();
    }
  };

  const rejectCall = () => {
    console.log('拒绝视频通话');
    if (socket) {
      socket.emit('video_call_reject', {
        fromUserId: currentUser.username,
        toUserId: otherUser.username,
      });
    }
    onCallStateChange?.('rejected');
    cleanupCall();
  };

  const endCall = () => {
    console.log('结束视频通话');
    if (socket) {
      socket.emit('video_call_end', {
        fromUserId: currentUser.username,
        toUserId: otherUser.username,
      });
    }

    const duration = callDuration;
    onCallEnded?.(duration);
    onCallStateChange?.('ended');
    cleanupCall();
  };

  const toggleMute = () => {
    if (localStream) {
      const audioTrack = localStream.getAudioTracks()[0];
      if (audioTrack) {
        audioTrack.enabled = !audioTrack.enabled;
        setIsMuted(!audioTrack.enabled);
      }
    }
  };

  const toggleVideo = () => {
    if (localStream) {
      const videoTrack = localStream.getVideoTracks()[0];
      if (videoTrack) {
        videoTrack.enabled = !videoTrack.enabled;
        setIsVideoEnabled(videoTrack.enabled);
      }
    }
  };

  const cleanupCall = () => {
    console.log('清理视频通话资源...');

    if (localStream) {
      localStream.getTracks().forEach(track => track.stop());
      setLocalStream(null);
    }

    if (peerConnectionRef.current) {
      peerConnectionRef.current.close();
      peerConnectionRef.current = null;
    }

    if (localVideoRef.current) {
      localVideoRef.current.srcObject = null;
    }
    if (remoteVideoRef.current) {
      remoteVideoRef.current.srcObject = null;
    }

    if (connectionTimeoutRef.current) {
      clearTimeout(connectionTimeoutRef.current);
      connectionTimeoutRef.current = null;
    }

    setRemoteStream(null);
    setIsCallActive(false);
    setIsIncoming(false);
    setIsConnecting(false);
    setIsMuted(false);
    setIsVideoEnabled(true);
    setCallDuration(0);
    setError(null);

    if (durationIntervalRef.current) {
      clearInterval(durationIntervalRef.current);
      durationIntervalRef.current = null;
    }
  };

  const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  if (!isVisible) return null;

  return (
    <div className="video-call-overlay">
      <div className="video-call-container">
        <div className="video-call-header">
          <div className="user-info">
            <img
              src={otherUser.image}
              alt={otherUser.username}
              className="user-avatar"
            />
            <div className="user-details">
              <h3>{otherUser.username}</h3>
              {isCallActive && (
                <p className="call-duration">{formatDuration(callDuration)}</p>
              )}
            </div>
          </div>
          <button onClick={onClose} className="close-button" title="关闭">
            ✕
          </button>
        </div>

        {error && (
          <div className="error-message">
            <strong>错误:</strong> {error}
          </div>
        )}

        <div className="video-container">
          <video
            ref={remoteVideoRef}
            autoPlay
            playsInline
            className="remote-video"
          />

          <div className="local-video-container">
            <video
              ref={localVideoRef}
              autoPlay
              playsInline
              muted
              className="local-video"
            />
          </div>

          {isConnecting && (
            <div className="connecting-overlay">
              <div className="connecting-content">
                <div className="connecting-spinner"></div>
                <p className="connecting-text">正在连接...</p>
              </div>
            </div>
          )}

          {isIncoming && (
            <div className="incoming-overlay">
              <div className="incoming-content">
                <img
                  src={otherUser.image}
                  alt={otherUser.username}
                  className="incoming-avatar"
                />
                <h3 className="incoming-name">{otherUser.username}</h3>
                <p className="incoming-call-text">视频通话来电</p>
                <div className="incoming-controls">
                  <button
                    onClick={rejectCall}
                    className="control-button reject-button"
                    title="拒绝"
                  >
                    ✕
                  </button>
                  <button
                    onClick={acceptCall}
                    className="control-button accept-button"
                    title="接听"
                  >
                    ✓
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>

        <div className="control-buttons">
          {isCallActive ? (
            <>
              <button
                onClick={toggleMute}
                className={`control-button mute-button ${isMuted ? 'muted' : ''}`}
                title={isMuted ? '取消静音' : '静音'}
              >
                {isMuted ? '🔇' : '🎤'}
              </button>
              <button
                onClick={toggleVideo}
                className={`control-button video-button ${!isVideoEnabled ? 'disabled' : ''}`}
                title={!isVideoEnabled ? '开启摄像头' : '关闭摄像头'}
              >
                {!isVideoEnabled ? '📹' : '📷'}
              </button>
              <button
                onClick={endCall}
                className="control-button hangup-button"
                title="挂断"
              >
                📞
              </button>
            </>
          ) : (
            !isIncoming && (
              <button
                onClick={endCall}
                className="control-button hangup-button"
                title="挂断"
              >
                📞
              </button>
            )
          )}
        </div>
      </div>
    </div>
  );
};

export default VideoCall;
